<template>
  <div class="app-container content">
    <span class="addTitle">{{ isEdit ? "新建考评任务" : "新建考评任务" }}</span>
    <el-divider />
    <span class="tab-title">考评任务信息</span>
    <el-form
      ref="ruleForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="top"
    >
      <p class="mt15"></p>
      <el-row>
        <el-col :span="10">
          <el-form-item label="考评任务名称" prop="taskName">
            <el-input
              v-model="form.taskName"
              placeholder="请输入考评任务名称"
              maxlength="50"
              show-word-limit
              clearable
              style="width: 400px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="考评库" prop="kesdId">
            <el-select
              v-model="form.kesdId"
              placeholder="请选择考评库名称"
              filterable
              readonly
              clearable
              style="width: 400px"
            >
              <el-option
                v-for="item in optionData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="考评任务环节">
            <span>新建</span>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="专家评分小组" prop="expertGroupId">
            <template #label>
              <span>专家评分小组</span>
              <el-link type="danger" :underline="false">（需选择有专家成员的小组，考评任务仅分发给专家成员打分）</el-link>
            </template>
            <el-input
              v-model="form.expertGroupId"
              placeholder="请选择小组"
              @click="groupDialog"
              clearable
              style="width: 400px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="专家评分截止日期" prop="endDate">
            <el-date-picker
              clearable
              v-model="form.endDate"
              type="date"
              style="width: 400px"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD"
              placeholder="提醒专家评分的截止日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span class="tab-title">关联任务</span>
    <el-form
      ref="dataLists"
      :model="forms"
      class="tableForm"
      :rules="rules"
      label-width="120px"
      label-position="top"
    >
      <el-row>
        <el-col>
          <el-table :data="forms.dataList" border class="borderTable">
            <el-table-column
              label="序号"
              align="center"
              type="index"
              width="55"
            />
            <el-table-column label="预评估任务名称" align="center">
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :rules="rules.ypgName"
                  :prop="`dataList.${scope.$index}.ypgName`"
                  label-width="0px"
                >
                  <el-input
                    v-model="scope.row.ypgName"
                    placeholder="请输入"
                    readonly
                    clearable
                    @click="openTaskReport(scope.row, scope.$index, 1)"
                  />
                </el-form-item>
                <span v-if="!scope.row.show">{{ scope.row.ypgName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="预评估任务地区"
              align="center"
              prop="provinceNames"
            >
            </el-table-column>
            <el-table-column
              label="简本报告"
              align="center"
              prop="jbReportId"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                {{ scope.row.jbReportName }}
              </template>
            </el-table-column>
            <el-table-column
              label="详本报告"
              align="center"
              prop="xbReportId"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                {{ scope.row.xbReportName }}
              </template>
            </el-table-column>
            <el-table-column
              label="现场调查任务名称"
              align="center"
              prop="xcdcId"
            >
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :rules="rules.xcdcName"
                  :prop="`dataList.${scope.$index}.xcdcName`"
                  label-width="0px"
                >
                  <el-input
                    v-model="scope.row.xcdcName"
                    placeholder="请输入"
                    readonly
                    clearable
                    @click="openTaskReport(scope.row, scope.$index, 2)"
                  />
                </el-form-item>
                <span v-if="!scope.row.show">{{ scope.row.xcdcName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="现场调查报告"
              align="center"
              prop="xcdcReportId"
              :show-overflow-tooltip="true"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                {{ scope.row.xcdcReportName }}
              </template>
            </el-table-column>
            <el-table-column
              label="报告版本修改"
              align="center"
              prop="report"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-space>
                  <el-link type="primary" :underline="false" @click="handleReportJb(scope.row)">简本</el-link>
                  <el-link type="primary" :underline="false" @click="handleReportXb(scope.row)">详本</el-link>
                  <el-link type="primary" :underline="false" @click="handleReportXcdc(scope.row)">现场调查报告</el-link>
                </el-space>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-space>
                  <el-link type="primary" :underline="false"
                    v-if="scope.row.id == '' || scope.row.show == true"
                    @click="handleApply(scope.row)"
                    >应用</el-link
                  >
                  <el-link type="primary" :underline="false"
                    v-if="scope.row.show == false"
                    @click="handleUpdate(scope.row)"
                    >修改</el-link
                  >
                  <el-link type="primary" :underline="false"
                    @click="handleDelete(scope.row, scope.$index)"
                    >删除</el-link
                  >
                </el-space>
              </template>
            </el-table-column>
            <template #append>
              <el-icon
                :size="22"
                color="var(--el-color-primary)"
                style="font-weight: bold; margin: 10px 0px; cursor: pointer"
                @click="handleAdd"
                ><Plus
              /></el-icon>
              <span style="cursor: pointer" @click="handleAdd">关联任务</span>
            </template>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div class="btnBox">
      <el-button plain @click="openTask = false">取消</el-button>
      <el-button plain @click="sureClean">清空</el-button>
      <el-button type="primary" @click="sureSave">保存</el-button>
    </div>
    <el-dialog
      :title="typeTask == 1 ? '预评估任务' : '现场调查任务'"
      v-model="openTask"
      width="1200px"
      append-to-body
    >
      <taskManageList
        :dialogVisible="openTask"
        @getSelectionTask="getSelectionTask"
        :typeStatus="typeTask"
        :tableChooseVal="tableChooseVal"
        v-if="typeTask == 1"
      />
      <manage
        :dialogVisible="openTask"
        v-if="typeTask == 2"
        :typeStatus="typeTask"
        :tableChooseVal="tableChooseVal"
        @getSelectionTask="getSelectionTask"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormSelect">确定</el-button>
          <el-button plain @click="openTask = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="分配小组"
      v-model="openGroup"
      width="900px"
      append-to-body
    >
      <p class="dialogTitle">分配小组</p>
      <el-form
        ref="groupRef"
        :model="formDialog"
        label-width="80px"
        :inline="true"
        class="addGroup"
      >
        <el-form-item label="小组名称" prop="groupName">
          <el-input
            v-model="formDialog.groupName"
            placeholder="请输入小组名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="小组组长" prop="groupLeader">
          <el-input
            v-model="formDialog.groupLeader"
            clearable
            placeholder="请输入小组组长"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="groupList" stripe row-key="id">
        <!-- <el-table-column type="selection" width="55" align="center" :reserve-selection="true" /> -->
        <el-table-column label="小组名称" align="center" prop="groupName" />
        <el-table-column label="小组组长" align="center" prop="groupLeader" />
        <el-table-column
          label="小组组员"
          align="center"
          prop="groupMember"
          show-overflow-tooltip
        />
        <el-table-column
          label="专家成员"
          align="center"
          prop="groupExpert"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleAllocation(scope.row)"
              >分配</el-link>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="formDialog.page"
        v-model:limit="formDialog.rows"
        @pagination="getGroupList"
      />
    </el-dialog>
    <!-- 版本选择 -->
    <el-dialog
      :title="
        typeReport == 1
          ? '简本报告版本选择'
          : typeReport == 2
          ? '详本报告版本选择'
          : '现场版本调查报告'
      "
      v-model="openReport"
      width="1200px"
      append-to-body
    >
      <el-table :data="reportList" border class="borderTable">
        <el-table-column label="序号" align="center" type="index" width="55" />
        <el-table-column label="报告类型" prop="type">
          <template #default="scope">
            <span v-if="scope.row.type == 1">简本报告</span>
            <span v-if="scope.row.type == 2">详本报告</span>
            <span v-if="scope.row.type == 3">现场调查报告</span>
          </template>
        </el-table-column>
        <el-table-column
          label="报告名称"
          prop="reportName"
          width="300"
        ></el-table-column>
        <el-table-column label="上传人" prop="uploadUserName"></el-table-column>
        <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button type="text" @click="handleChoose(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="openReport = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="addAppraisalTaskManagement">
import { getGroup } from "@/api/taskmanage/group.js";
import {
  getLatestUnsaveTask,
  applyGlTask,
  deleteGlTask,
  cleanKpTask,
  saveKpTask,
  getReportListByjb,
  getReportListByxb,
  getReportListByxcdc,
} from "@/api/workEvaluation/appraisalTaskManagement/appraisalTaskManage.js";
import { getAllAppraisal } from "@/api/workEvaluation/evaluationStandardSetup/appraisalDatabaseManage.js";
import taskManageList from "../Components/taskManageList";
import manage from "../Components/manage";
import { useRouter, useRoute } from "vue-router";
import { nextTick, onMounted, reactive } from "vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const isEdit = ref(false);
const optionData = ref([]);
const openTask = ref(false);//预评估任务模态框
const openGroup = ref(false);
const openReport = ref(false);
const loading = ref(true);
const ind = ref();
const ruleForm = ref();
const typeReport = ref(0);
const typeTask = ref(0);
const reportList = ref([]);
const currentVal = ref({});
const selectTask = ref({});
const selectObj = ref({});
const total = ref(0);
const tableChooseVal = ref();
const data = reactive({
  form: {},
  forms: {
    dataList: [],
    page: 1,
    rows: 10,
  },
  groupList: [],
  formDialog: {
    page: 1,
    rows: 10,
    groupName: undefined,
    groupLeader: undefined,
    groupMember: undefined,
    groupExpert: undefined,
  },
});
const { groupList, form, forms, formDialog } = toRefs(data);
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
};
const rules = ref({
  taskName: [{ required: true, message: "请输入考评任务名称", trigger: "blur" }],
  kesdId: [{ required: true, message: "请选择考评库名称", trigger: "change" }],
  expertGroupId: [{ required: true, message: "请选择专家评分小组", trigger: "change" }],
  endDate: [{ required: true, message: "请选择截止日期", trigger: "change" }],
  ypgName: [ { required: true, message: "请选择预评估任务名称", trigger: "change" }],
  xcdcName: [{ required: true, message: "请选择现场调查任务名称", trigger: "change" }]
});

// 获取用户上次未保存的任务
const getData = () => {
  getLatestUnsaveTask().then((res) => {
    if (res.data.name !== null) {
      form.value.endDate = res.data.endDate;
      form.value.taskName = res.data.name;
      form.value.kesdId = res.data.kesdId;
      form.value.expertGroupId = res.data.expertGroupName;
      form.value.groupId = res.data.expertGroupId;
      forms.value.dataList = res.data.taskList;
    } else {
      form.value = {};
      forms.value.dataList = [];
    }
  });
};
/** 查询小组列表 */
function getGroupList() {
  loading.value = true;
  getGroup(formDialog.value).then((response) => {
    groupList.value = response.data.result;
    total.value = response.data.total;
    loading.value = false;
  });
}
const handleAdd = () => {
  proxy.$refs["ruleForm"].validate((valid) => {
    if (valid) {
      forms.value.dataList.push({
        id: "",
        ypgId: "",
        ypgName: "",
        provinceNames: "",
        provinceIdList: [],
        xcdcId: "",
        xcdcName: "",
        jbReportId: "",
        xbReportId: "",
        xcdcReportId: "",
        show: true,
      });
    } else {
      return false;
    }
  });
};
const openTaskReport = (row, index, type) => {
  ind.value = index;
  selectTask.value = {};
  selectObj.value = {};
  typeTask.value = type;
  openTask.value = true;
  if(type==1){
    tableChooseVal.value=row
  }else if(type==2){
    tableChooseVal.value=row
  }
};
//提交
const getSelectionTask = (val) => {
  if (val[0]) {
    if (typeTask.value == 1) {
      selectTask.value = JSON.parse(JSON.stringify(val[0]));
    } else {
      selectObj.value = JSON.parse(JSON.stringify(val[0]));
    }
  }
};
//确定
const submitFormSelect = () => {
  nextTick(() => {
    if (JSON.stringify(selectTask.value) != "{}") {
      const obj = selectTask.value;
      tableChooseVal.value=selectTask.value
      forms.value.dataList[ind.value].ypgName = obj.taskName;
      forms.value.dataList[ind.value].ypgId = obj.id;
      forms.value.dataList[ind.value].provinceNames = obj.provinceNames;
      forms.value.dataList[ind.value].provinceIdList = obj.provinceIdList;
      //简本
      getReportListByjb({
        id: forms.value.dataList[ind.value].ypgId,
        page: forms.value.page,
        rows: forms.value.rows,
      }).then((res) => {
        forms.value.dataList[ind.value].jbReportId = res.data.rows[0].id;
        forms.value.dataList[ind.value].jbReportName =
          res.data.rows[0].reportName;
      });
      //详本
      getReportListByxb({
        id: forms.value.dataList[ind.value].ypgId,
        page: forms.value.page,
        rows: forms.value.rows,
      }).then((res) => {
        forms.value.dataList[ind.value].xbReportId = res.data.rows[0].id;
        forms.value.dataList[ind.value].xbReportName =
          res.data.rows[0].reportName;
      });
      openTask.value = false;
    }
    if (JSON.stringify(selectObj.value) != "{}") {
      const obj = selectObj.value;
      tableChooseVal.value=selectObj.value
      forms.value.dataList[ind.value].xcdcName = obj.taskName;
      forms.value.dataList[ind.value].xcdcId = obj.id;
      openTask.value = false;
      getReportListByxcdc({
        id: forms.value.dataList[ind.value].xcdcId,
        page: forms.value.page,
        rows: forms.value.rows,
      }).then((res) => {
        forms.value.dataList[ind.value].xcdcReportId = res.data.rows[0].id;
        forms.value.dataList[ind.value].xcdcReportName =
          res.data.rows[0].reportName;
      });
    }
  });
};
// 点击简本
const handleReportJb = (val) => {
  currentVal.value = val;
  typeReport.value = 1;
  if (val.ypgId == null || val.ypgId == "") {
    proxy.$modal.msgWarning("请先选择预评估任务");
  } else {
    getReportListByjb({
      id: val.ypgId,
      page: forms.value.page,
      rows: forms.value.rows,
    }).then((res) => {
      reportList.value = res.data.rows;
      openReport.value = true;
    });
  }
};
// 点击详本
const handleReportXb = (val) => {
  currentVal.value = val;
  typeReport.value = 2;
  if (val.ypgId == null || val.ypgId == "") {
    proxy.$modal.msgWarning("请先选择预评估任务");
  } else {
    getReportListByxb({
      id: val.ypgId,
      page: forms.value.page,
      rows: forms.value.rows,
    }).then((res) => {
      reportList.value = res.data.rows;
      openReport.value = true;
    });
  }
};
// 点击现场调查
const handleReportXcdc = (val) => {
  currentVal.value = val;
  typeReport.value = 3;
  if (val.xcdcId == null || val.xcdcId == "") {
    proxy.$modal.msgWarning("请先选择现场调查任务");
  } else {
    getReportListByxcdc({
      id: val.xcdcId,
      page: forms.value.page,
      rows: forms.value.rows,
    }).then((res) => {
      reportList.value = res.data.rows;
      openReport.value = true;
    });
  }
};
// 报告选择
const handleChoose = (val) => {
  if (typeReport.value == 1) {
    currentVal.value.jbReportName = val.reportName;
    currentVal.value.jbReportId = val.id;
  } else if (typeReport.value == 2) {
    currentVal.value.xbReportName = val.reportName;
    currentVal.value.xbReportId = val.id;
  } else {
    currentVal.value.xcdcReportName = val.reportName;
    currentVal.value.xcdcReportId = val.id;
  }
  openReport.value = false;
};

//选择小组
const groupDialog = () => {
  openGroup.value = true;
  formDialog.value.groupName=''
  formDialog.value.groupLeader=''
  formDialog.value.page = 1;
  getGroupList();
};
const handleQuery = () => {
  getGroupList();
};
const handleReset = () => {
  proxy.resetForm("groupRef");
  handleQuery();
};
//分配
const handleAllocation = (val) => {
  form.value.expertGroupId = val.groupName;
  form.value.groupId = val.id;
  openGroup.value = false;
};
// 删除单行
const handleDelete = (val) => {
  if(val.id==''||val.id==null){
    let index = forms.value.dataList.indexOf(val);
    if (index !== -1) {
      forms.value.dataList.splice(index, 1);
    } 
    }
 else {
    deleteGlTask({ id: val.id }).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess("删除成功");
        appraisalList();
      }
    });
  }
};
// 应用
const handleApply = (val) => {
  proxy.$refs["dataLists"].validate((valid) => {
    if (valid) {
      form.value.expertGroupName = form.value.expertGroupId;
      form.value.expertGroupId = form.value.groupId;
      const obj = { ...form.value, list: forms.value.dataList };
      applyGlTask(obj).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("应用成功");
          appraisalList();
        }
      });
    } else {
      return false;
    }
  });
};
// 修改
const handleUpdate = (val) => {
  val.show = true;
};
// 清空
const sureClean = () => {
  proxy.$modal
    .confirm("是否确认清空该数据项？")
    .then(function () {
      //   return deleteThreeLevelIndexList({id:id.join(',')});
      cleanKpTask().then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("清空成功");
          appraisalList();
        }
      });
    })
    .catch(() => {});
};
// 保存
const sureSave = () => {
  proxy.$refs["ruleForm"].validate((valid) => {
    if (valid) {
      dataListCheck("dataLists");
    } else {
      return false;
    }
  });
};
const dataListCheck = (formRef) => {
  proxy.$refs[formRef].validate((valid) => {
    if (valid) {
      let isCommitVal = forms.value.dataList.every((val) => val.show == false);
      if (isCommitVal == false) {
        proxy.$modal.msgWarning("有未点击应用的数据,请先点击应用");
      } else {
        saveKpTask().then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess("保存成功");
            router.push({
              path: "/workEvaluation/appraisalTaskManagement/appraisalTaskManage",
            });
            // appraisalList();
          }
        });
      }
    } else {
      return false;
    }
  });
};

const appraisalList = () => {
  getAllAppraisal()
    .then((res) => {
      if (res.data && res.data.length > 0) {
        optionData.value = res.data;
        getData();
      }
    })
    .catch((err) => {});
};

onMounted(() => {
  if (!route.query.metaTitle) {
    isEdit.value = false;
  } else {
    isEdit.value = true;
  }
  appraisalList();
});
</script>

<style scoped lang="scss">
:deep(.el-table).borderTable td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
  .cell {
    height: 68px;
    line-height: 68px;
    .el-form-item {
      position: relative;
      top: 18px;
      .el-input__suffix {
        top: 9px;
      }
    }
  }
}
.tableForm {
  padding: 20px 0;
  box-sizing: border-box;
}
.btnBox {
  width: 100%;
  text-align: center;
  padding: 20px 0;
}
.content {
  min-width: 1200px;
}
.addTitle {
  font-size: 22px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.tab-title {
  font-size: 18px;
  font-weight: bold;
  border-left: 4px solid var(--el-color-primary);
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}

:deep(.el-divider--horizontal) {
  margin: 20px 0;
}
:deep(.el-table__append-wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
}
:deep(.el-table).borderTable td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
}
</style>
